<?php
namespace App\Utility;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\Utility\Time;
class Sms
{

    private static $instance = null;
    private $appkey;
    private $appCode;
    private $appSecret;
    private $sendSms = "http://39.97.4.102:9090/sms/batch/v1";



    private function __construct($appkey,$appCode,$appSecret)
    {
        $this->appkey       = $appkey;
        $this->appCode      = $appCode;
        $this->appSecret    = $appSecret;
    }

    public static function getInstance($appkey = "",$appCode="",$appSecret="")
    {
        if(self::$instance === null){
            self::$instance = new self($appkey,$appCode,$appSecret);
        }
        return self::$instance;
    }



    /**
     * 发送短信
     * @param $mobile
     * @param $code
     * @return bool
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function sendSms($mobile,$title ,$code){

        $http = new HttpClient($this->sendSms);

        $timestamp = msectime();
        $msg =    "$title 尊敬的用户您好,您的手机验证码为: $code,有效期15分钟,请妥善保管请勿泄露他人！";
        $params = [
            "appkey" => $this->appkey ,
            "appcode"=> $this->appCode,
            "sign"   =>"",
            "uid"    => getRandom(32),
            "phone"  => $mobile,
            "msg"    => $msg,
            "timestamp"=> $timestamp,
            "extend"=>"",
        ];

        $params['sign'] = md5($this->appkey. $this->appSecret.$timestamp);

        $res = $http->postJson(json_encode($params));

        $data = json_decode($res->getBody(),true);

        if($data['code'] != 00000){

            return ['code'=> 400 ,'msg' => $data['desc']];
        }

        return ['code'=> 200 ,'msg' => '成功!'];

    }
}

?>